<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>Canvas Example 3 (Sprite Animation Alt)</title>
		
		<script src="timer.js" charset="utf-8"></script>
		<script src="sprite.js" charset="utf-8"></script>
		<script>
			var Keys = {
				getDown: [],
		    	UP: 38,
		    	DOWN: 40,
		    	LEFT: 37,
		    	RIGHT: 39,
		    	C: 67
		    }
			
			window.onload = function() {
				var canvas = document.getElementById('myCanvas');
				var c = canvas.getContext('2d');
				
				// Initialize our sprite array
				var spritesheet = ['../img/char1.png', '../img/char2.png', '../img/char3.png'];
				var currentHero = 0;

				// Preload the sprite images
				for (var i = 0; i < spritesheet.src; i++) {
					var i = new Image();
					i.src = spritesheet[i];
				}

				
				var hero = new Sprite(spritesheet[currentHero], 32, 32, 0, 128, 4, 0);

				var timer = new Timer();
				var Speed = {
					x: 0,
					y: 0,
					MAX: 2,
					FRICTION: 0.25,
					INCREASE: 0.25
				}
				var Position = {
					x: 130,
					y: 130
				}

				draw(timer.getSeconds());

			    window.addEventListener('keydown', handleKeyDown, false);
			    window.addEventListener('keyup', handleKeyUp, false);

			    function handleKeyDown(e) {
			    	switch (e.keyCode) {
			    		case Keys.LEFT:
		                    if (!inArray(Keys.RIGHT, Keys.getDown) && !inArray(Keys.LEFT, Keys.getDown)) {
		                        Keys.getDown.push(Keys.LEFT);
		                    }
		                    break;
		               case Keys.RIGHT:
		                    if (!inArray(Keys.LEFT, Keys.getDown) && !inArray(Keys.RIGHT, Keys.getDown)) {
		                        Keys.getDown.push(Keys.RIGHT);
		                    }
		                    break;
		                case Keys.UP:
		                    if (!inArray(Keys.UP, Keys.getDown) && !inArray(Keys.DOWN, Keys.getDown)) {
		                        Keys.getDown.push(Keys.UP);
		                    }
		                    break;
		                case Keys.DOWN:
		                    if (!inArray(Keys.DOWN, Keys.getDown) && !inArray(Keys.UP, Keys.getDown)) {
		                        Keys.getDown.push(Keys.DOWN);
		                    }
		                    break;
			    	}
			    }

			    function handleKeyUp(e) {
			    	switch (e.keyCode) {
			    		case Keys.C:
			    			if (currentHero === (spritesheet.length - 1)) {
			    				currentHero = 0;
			    			} else {
			    				currentHero++;
			    			}
			    			
			    			hero.setSpritesheet(spritesheet[currentHero]);
			    			break;
			    		case Keys.LEFT:
			    		case Keys.RIGHT:
			    		case Keys.UP:
			    		case Keys.DOWN:
		                    Keys.getDown = removeFromArray(e.keyCode, Keys.getDown);
		                    break;
			    	}
			    }

			    function inArray(element, arr) {
				    for (var i = 0; i < arr.length; i++) {
				        if (arr[i] === element) {
				            return true;
				        }
				    }    
				    return false;
				}

				function removeFromArray(element, arr) {
				    for (var i = 0; i < arr.length; i++) {
				        if (arr[i] == element)
				            arr.splice(i, 1);
				    }
				    
				    return arr;
				}

				function calculateSpriteOffset(x, y) {
					if (x === 0 && y === 0) { // standing still
						hero.setOffset(0, 128);
						hero.setFrames(1);
						hero.setDuration(0);
					} else if (x > 0 && y === 0) { // East
						if (hero.offsetY !== 192) {
							hero.setOffset(0, 192);
							hero.setFrames(6);
							hero.setDuration(500);
						}
					} else if (x < 0 && y === 0) { // West
						if (hero.offsetY !== 224) {
							hero.setOffset(0, 224);
							hero.setFrames(6);
							hero.setDuration(500);
						}
					} else if (x === 0 && y > 0) { // South
						if (hero.offsetY !== 128 || hero.frames !== 4) {
							hero.setOffset(0, 128);
							hero.setFrames(4);
							hero.setDuration(500);
						}
					} else if (x === 0 && y < 0) { // North
						if (hero.offsetY !== 160) {
							hero.setOffset(0, 160);
							hero.setFrames(4);
							hero.setDuration(500);
						}
					} else if (x > 0 && y < 0) { // North East
						if (hero.offsetY !== 0) {
							hero.setOffset(0, 0);
							hero.setFrames(4);
							hero.setDuration(500);
						}
					} else if (x > 0 && y > 0) { // South East
						if (hero.offsetY !== 32) {
							hero.setOffset(0, 32);
							hero.setFrames(4);
							hero.setDuration(500);
						}
					} else if (x < 0 && y < 0) { // North West
						if (hero.offsetY !== 64) {
							hero.setOffset(0, 64);
							hero.setFrames(4);
							hero.setDuration(500);
						}
					} else if (x < 0 && y > 0) { // South West
						if (hero.offsetY !== 96) {
							hero.setOffset(0, 96);
							hero.setFrames(4);
							hero.setDuration(500);
						}
					}
				}
				
				function draw (timeStamp) {				
					timer.update();

					c.fillStyle = '#FFFFFF';
					c.fillRect (0, 0, canvas.width, canvas.height);

					c.fillStyle = '#000000';
					c.font = '12px Arial, Sans-serif';
					c.fillText ("Use the UP, DOWN, LEFT and RIGHT keys to ", 10, 20);
					c.fillText ("move the character. Press the C key to change", 10, 40);
					c.fillText ("the texture.", 10, 60);

					
					// Calculate X speed
					if (inArray(Keys.RIGHT, Keys.getDown)) {
				    	Speed.x += (Speed.x <= Speed.MAX) ? Speed.INCREASE : 0;
				    } else if (inArray(Keys.LEFT, Keys.getDown)) {
				    	Speed.x -= (Speed.x >= (Speed.MAX * -1)) ? Speed.INCREASE : 0;
				    } else {
				        // No right / left keys are being pressed
				        if (Speed.x > 0) {
				        	Speed.x += Speed.FRICTION * -1;
				        	Speed.x = (Speed.x < 0) ? 0 : Speed.x;
				        } else if (Speed.x < 0) {
					        Speed.x += Speed.FRICTION;
					        Speed.x = (Speed.x > 0) ? 0 : Speed.x;
					    }
				    }

				    // Calculate Y speed
				    if (inArray(Keys.DOWN, Keys.getDown)) {
				    	Speed.y += (Speed.y <= Speed.MAX) ? Speed.INCREASE : 0;
				    } else if (inArray(Keys.UP, Keys.getDown)) {
				    	Speed.y -= (Speed.y >= (Speed.MAX * -1)) ? Speed.INCREASE : 0;
				    } else {
				        // No up / down keys are being pressed
				        if (Speed.y > 0) {
				        	Speed.y += Speed.FRICTION * -1;
				        	Speed.y = (Speed.y < 0) ? 0 : Speed.y;
				        } else if (Speed.y < 0) {
					        Speed.y += Speed.FRICTION;
					        Speed.y = (Speed.y > 0) ? 0 : Speed.y;
					    }
				    }

				    // Change the X/Y offset of the spritesheet and the "speed" of the animation depending on X/Y speed
				    calculateSpriteOffset(Speed.x, Speed.y);

				    // Make sure to restraint the character to move inside the canvas
				    if ((Position.x + Speed.x) > 0 && (Position.x + Speed.x) < (canvas.width - hero.width)) {
				    	Position.x += Speed.x;
					}

					if ((Position.y + Speed.y) > 0 && (Position.y + Speed.y) < (canvas.height - hero.height)) {
				    	Position.y += Speed.y;
					}

					hero.setPosition(Position.x, Position.y);
					hero.animate(c, timer);
					hero.draw(c);

					setTimeout(function() {
						draw(timer.getSeconds());
					}, 5);
				}
			}
		</script>		
    </head>
    <body>
		<canvas id="myCanvas" width="300" height="300" style="border: 1px solid black;">
			Your browser doesn't include support for the canvas tag.
		</canvas>
    </body>
</html>